<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace Model\UserBundle\Model;

use Base\BaseModel;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Model\UserBundle\Setting\UserLoginLogSetting;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;

class UserLoginLogModel extends BaseModel {


    /*
     * 列表基本设置【通用模块必须】
     */
    public function listSettingDefault()
    {
        $settings = new UserLoginLogSetting($this->getDoctrine());
        return $settings->listConfig();
    }

    public function getLastLoginInfo($account)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")->from("UserLoginLog")->where("userAccount = :account")->setParameter("account",$account);
        $qb->orderBy("id","desc");
        $log = $qb->execute()->fetch();
        return $log;
    }

    public function createLoginLogInfo($user = NULL)
    {
        if ($user instanceof UserInterface) {
            $username = $user->getUsername();
            $password = $user->getPassword();
        } else {
            $param = Request::createFromGlobals();
            $username = $param->request->get("_username");
            $password = $param->request->get("_password");
            $password = md5($password);
        }

        $loginInfo = array(
            "userAccount"    => $username,
            "loginTime"      => time(),
            "loginIp"        => $_SERVER["REMOTE_ADDR"],
            "loginRequest"   => json_encode($_REQUEST),
            "userAgent"      => $_SERVER["HTTP_USER_AGENT"],
        );
        $userModel = new UserModel($this->getDoctrine());
        $user = $userModel->checkAccountPassword($username,$password);
        if (!empty($user))
        {//账号密码匹配成功
            $lastLoginLog = $this->getLastLoginInfo($username);
            $loginInfo["passwordError"] = 0;
            $data = array(
                "lastLoginTime" => $lastLoginLog["loginTime"],
                "lastLoginIp" => $lastLoginLog["loginIp"],
            );
            $userModel->updateUserInfo($user["id"],$data);
        } else {
            $loginInfo["passwordError"] = 1;
        }
        return $loginInfo;
    }

    public function addLoginLog($loginInfo)
    {
        $qb = $this->getQueryBuilder();
        $qb->insert("UserLoginLog");
        foreach ($loginInfo as $key => $val) {
            $qb->setValue("$key",":$key")->setParameter("$key",$val);
        }
        $qb->execute();
    }

}